<template>
    <div class="add-to" v-if="is_show">
        <div id="add-to" :class="show_class">

            <!--S标题-->
            <h2>
                追加红包
                <i class="close iconfont icon-guanbi"
                   @click="$emit('close')"
                >
                </i>
            </h2>
            <!--E标题-->

            <!--S支付金额|手续费|红包总额-->
            <i-header
                    class="header"
                    :charge="charge"
                    :total="total"
                    :pay="pay"
            ></i-header>
            <!--E支付金额|手续费|红包总额-->

            <cube-form
                    ref="form"
                    :model="model"
                    :schema="schema"
                    @submit="submit"
            ></cube-form>

        </div>
    </div>
</template>

<script>
import IHeader from '../header'
export default {
    name: "add-to",
    data() {
      return {
          show_class: 'hide',
          model: {
            number: null,
            money: null
          },
          schema: {},
          add_to_id:0
      }
    },
    components: {
        IHeader
    },
    props: {
        // 是否显示
        is_show: {
            type: Boolean,
            default: false
        },
        // 红包id
        red_id: {
          type: Number,
          default: 0
        },
        // 手续费
        ratio: {
            default: ''
        },
        // 单个红包金额
        money: {
          type: String
        },
        // 红包类型
        type: {
            type: Number
        }
    },
    watch: {
      is_show() {
          this.toggle()
          this.createForm()
      }
    },
    computed: {
        // 红包总额
        total() {
            if(!this.model.number || (!this.model.money && this.type === 2)) {
                return '0.00';
            }
            if(this.type === 1){
                //普通红包  总额=金额*红包数量
                return (parseFloat(this.money) * parseInt(this.model.number)).toFixed(2);
            }else{
                //手气红包  总额 = 金额;
                return parseFloat(this.model.money).toFixed(2);
            }
        },
        // 手续费
        charge(){
            return this.ratio === 0 ? '0.00' : (this.total * this.ratio).toFixed(2)
        },
        //支付总额
        pay(){
            if(!this.model.number) {
                return '0.00';
            } else {
                return (parseFloat(this.total) + parseFloat(this.charge)).toFixed(2)
            }
        },
        data() {
            let data = {
                charge: this.charge,
                pay: this.pay,
                number: this.model.number
            }
            if(this.model.money) {
                data.money = this.model.money
            }
            return data
        }
    },
    methods: {
        toggle() {
            if(this.is_show) {
                setTimeout(() => {
                    this.show_class = 'show'
                },10)
                this.show_class = 'hide'
            }
        },
        createForm() {
            let fields = [
                {
                    type:'input',
                    modelKey:'number',
                    label:'红包个数',
                    props:{
                        type:'text',
                        placeholder:'填写个数'
                    },
                    rules:{
                        required:true,
                        type:'number',
                        max:1000000,
                        min:1,
                        pattern:/^\d+$/
                    },
                    messages:{
                        required:'请输入红包个数',
                        type:'请输入正确的红包个数',
                        max:'红包个数不能超过一百万',
                        min:'请输入正确的红包个数',
                        pattern:'请输入正确的红包个数'
                    }
                },
                {
                    type: 'button',
                    label: '确认追加',
                    events: {
                        click: () => {
                            this.$refs.form.submit()
                        }
                    }
                }
            ]
            if(this.type === 2) {
                fields.unshift({
                    type:'input',
                    modelKey:'money',
                    label:'红包总额',
                    props:{
                        type:'text',
                        placeholder: '红包总额'
                    },
                    rules:{
                        required:true,
                        type:'number',
                        pattern:/(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/
                    },
                    messages:{
                        required:'请输入红包金额',
                        type:'请输入正确的红包金额',
                        pattern:'请输入正确的红包金额'
                    }
                })
            }
            this.schema.fields = fields
        },
        submit() {
            if(!this.submitCheck()) return false;
            this.$post('addTo', {
                red_id: this.red_id,
                data: this.data
            })
                .then((res) => {
                    let { code, data, err_msg, pay_params } = res.data
                    if(!code) {
                        if(pay_params) {
                            this.add_to_id = data
                            if(process.env.NODE_ENV === 'development'){
                                this.wxPaySuccess()
                            } else {
                                this.wxPay(pay_params)
                            }
                        } else {
                            this.$emit('addTo',this.model)
                            this.$emit('close')
                        }
                    } else {
                        this.$createToast({
                            time: 1500,
                            txt: err_msg ? err_msg : '追加红包失败',
                            mask: true,
                            type: 'error',
                        }).show()
                    }
                })
        },
        /**
         * 提交验证
         */
        submitCheck() {
            // 手气红包时单个红包金额不能小于0.01元
            if(this.type === 2) {
                // 手气红包时单个红包金额不能小于0.01元
                if(parseFloat(this.model.money) / parseInt(this.model.number) < 0.01){
                    this.$createToast({
                        time: 2000,
                        txt: '单个红包金额不能小于0.01元',
                        type: 'error'
                    }).show()
                    return false;
                }
            }
            return true;
        },
        /**
         * 发红包微信支付成功
         */
        wxPaySuccess() {
            this.$post("addTo/wxPaySuccess",{
                add_to_id: this.add_to_id
            })
                .then((res) => {
                    console.log(res)
                });
        },
        /**
         * 微信支付
         */
        wxPay(params) {
            this.$wx.chooseWXPay({
                timestamp: params.timeStamp,
                nonceStr: params.nonceStr,
                package: params.package,
                signType: params.signType,
                paySign: params.paySign,
                success: ()=>{
                    this.wxPaySuccess()
                },
                cancel: () => {
                    this.wxPayFail()
                },
                fail:()=>{
                    this.wxPayFail()
                }
            });
        },
        /**
         * 追加红包支付失败
         */
        wxPayFail() {
            this.$createToast({
                time: 1500,
                txt: '发红包失败',
                type:'error',
                mask:true,
                onTimeout: () => {
                    this.$post("sendRed/wxPayFail",{
                        add_to_id: this.add_to_id
                    })
                        .then((res) => {
                            console.log(res)
                        });
                }
            }).show();
        }
    }
}
</script>

<style scoped lang="less">
    @import "@/theme.less";
    .add-to{
        position: fixed;
        top:0;
        left:0;
        z-index: 1000000;
        width: 100%;
        height: 100%;
        background: rgba(0,0,0,0.5);
        #add-to{
            position: absolute;
            left:12.5px;
            top:50%;
            transition: .1s;
            width: 350px;
            background: #fff;
            color: #fff;
            &.show{
                transform: translateY(-50%) scale(1);
            }
            &.hide{
                transform: translateY(-50%) scale(0);
            }
            h2{
                width: 100%;
                height: 40px;
                line-height: 40px;
                background: @main-color1;
                text-align: center;
                .close{
                    position: absolute;
                    right: 0;
                    top:0;
                    width: 40px;
                }
            }
        }
        .header{
            position:static;
        }
    }
</style>